package zpy.servlet.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import zpy.servlet.pojo.ErrorMessage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;



/**
 * Servlet implementation class FileDownloadServlet
 */
@WebServlet("/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final int PATY_TYPE_PART = 1;//相对路径
	private static final int PATY_TYPE_FULL = 2;//全路径
   
	 private static Map<String,String> contentTypeMap = new HashMap<String,String>();  
	    static{
	    	contentTypeMap.put("doc", "application/msword");
	    	contentTypeMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
	    	contentTypeMap.put("pdf", "application/pdf");
	    	contentTypeMap.put("jpg", "image/jpg");
	    	contentTypeMap.put("jpeg", "image/jpeg");
	    	contentTypeMap.put("xls", "application/vnd.ms-excel");
	    	contentTypeMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
	    	contentTypeMap.put("txt", "text/plain");
	    	contentTypeMap.put("asm", "text/x-asm");
	    	contentTypeMap.put("rar", "application/x-rar-compressed");
	    	contentTypeMap.put("zip", "application/zip");
	    	contentTypeMap.put("ppt", "application/vnd.ms-powerpoint");
	    	contentTypeMap.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
	    
	    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取下载文件的绝对路径
		String filepath = request.getParameter("filepath");
		String strPathType = request.getParameter("pathType");
		int pathType = Integer.parseInt(strPathType);
		
		if (pathType == PATY_TYPE_PART) {
			filepath = getServletContext().getInitParameter("file_download_path")
					+ filepath;
		}
		//设置响应正文的MIME类型
		String  fileName    = filepath.substring(filepath.lastIndexOf("\\")+1);
		String  suffix      = fileName.substring(fileName.lastIndexOf(".")+1);
		String  contentType = contentTypeMap.get(suffix);
		String path = request.getContextPath();
		String basePath = request.getScheme() 
				+ "://" + request.getServerName() 
				+ ":" + request.getServerPort() + path + "/";
		if (contentType == null) {
			//contentType = "";
			ErrorMessage error = new ErrorMessage("文件下载失败",
					"无法处理的文件类型",
					"你下载的"+filepath+"后台不提供该类型的文件下载",basePath
					+"/pages/file_download/download.jsp");
			request.setAttribute("error", error);
			//转发到错误提示页面
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/public/error.jsp")
			       .forward(request, response);
			return;
		}
	
		 //打开文件
		File file = new File(filepath);
		if (!file.exists()) {
			ErrorMessage error = new ErrorMessage("文件下载失败",
					"无法处理的文件类型",
					"你下载的"+filepath+"后台不提供该类型的文件下载",basePath
					+"/pages/file_download/download.jsp");
			request.setAttribute("error", error);
			//转发到错误提示页面
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/public/error.jsp")
			       .forward(request, response);
			return;
		}
		//设置响应正文的MIME类型，设置Context-Disposition
		response.setContentType(contentType);
		//设置下载文件的默认文件名
		fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		//告诉客户端下载文件  
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1)  
		{  //解决火狐中文件名为中文时的乱码问题
		  response.setHeader("Content-Disposition", "attachment; filename*=''" + fileName);  
		} 
		else 
		{  //其他浏览器处理            
			response.setHeader("content-disposition", "attachment; filename=" + fileName);  
		}  
		InputStream inputStream = new FileInputStream(file);
		//创建响应正文二进制输出流
		OutputStream outputStream = response.getOutputStream();
		//将文件写入响应正文输出流
		byte[] buf = new byte[8192];
		int len = 0;
		while((len = inputStream.read(buf))!=-1){
			outputStream.write(buf, 0, len);
		}
		inputStream.close();
		outputStream.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
